package com.app.micaihu.listener;

import android.graphics.drawable.Animatable;

import com.app.micaihu.custom.view.CustomImageView;
import com.app.utils.util.ViewSizeUtils;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.imagepipeline.image.ImageInfo;

/**
 * Created by Guo on 2016/11/2.
 *
 * 根据给定的宽，来自动适应高的 fresco 的监听
 */
public class AutoHeightControllerListener <INFO> extends BaseControllerListener<INFO> {

    private CustomImageView mCustomImageView;
    private float maxRatio;//最大的宽高比例
    private float minRatio;//最小的宽高比例
    private int maxWidth;


    public AutoHeightControllerListener(CustomImageView mCustomImageView) {
        this.mCustomImageView = mCustomImageView;
    }

    public AutoHeightControllerListener(CustomImageView mCustomImageView,int maxWidth) {
        this.mCustomImageView = mCustomImageView;
        this.maxWidth = maxWidth;
    }

    public AutoHeightControllerListener(CustomImageView mCustomImageView, float maxRatio,float minRatio) {
        this.mCustomImageView = mCustomImageView;
        this.maxRatio = maxRatio;
        this.minRatio = minRatio;
    }


    @Override
    public void onFinalImageSet(String id, INFO imageInfo, Animatable animatable) {
        super.onFinalImageSet(id, imageInfo, animatable);

        if (imageInfo == null) {
            return;
        }
        if (imageInfo instanceof ImageInfo) {
            ImageInfo imageInfo1 = (ImageInfo) imageInfo;
            int height = imageInfo1.getHeight();
            int width = imageInfo1.getWidth();
            float rate = (float) width / (float) height;
            if(maxWidth > 0){
                mCustomImageView.setMaxWidth(maxWidth);
            }else{
                mCustomImageView.setMaxWidth(ViewSizeUtils.getWidthPixels());
            }

            float aspectRatio = mCustomImageView.getAspectRatio();

            if (aspectRatio != rate) {
                if(minRatio > 0 && rate < minRatio){
                    mCustomImageView.setAspectRatio(minRatio);
                }else if(minRatio > 0 && rate > maxRatio){
                    mCustomImageView.setAspectRatio(maxRatio);
                }else{
                    mCustomImageView.setAspectRatio(rate);
                }
            }

        }
    }
}
